package com.usian.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.usian.common.BaseServiceimpl;
import com.usian.common.constans.wemedia.WemediaContans;
import com.usian.common.message.NewsAutoScanConstants;
import com.usian.model.admin.dtos.NewsAuthDto;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmNewsDto;
import com.usian.model.media.dtos.WmNewsPageReqDto;
import com.usian.model.media.pojos.WmMaterial;
import com.usian.model.media.pojos.WmNews;
import com.usian.model.media.pojos.WmNewsMaterial;
import com.usian.model.media.pojos.WmUser;
import com.usian.model.media.vo.WmNewsVo;
import com.usian.utils.threadlocal.WmThreadLocalUtils;
import com.usian.wemedia.mapper.WmMaterialMapper;
import com.usian.wemedia.mapper.WmNewsMapper;
import com.usian.wemedia.mapper.WmNewsMaterialMapper;
import com.usian.wemedia.mapper.WmUserMapper;
import com.usian.wemedia.service.WmNewsService;
import io.swagger.models.auth.In;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class WmNewsServiceImpl extends BaseServiceimpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Value("${fdfs.url}")
    private String fileServerUrl;
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Autowired
    private WmMaterialMapper wmMaterialMapper;
    @Autowired
    private KafkaTemplate kafkaTemplate;
    @Autowired
    private WmNewsMapper wmNewsMapper;
    @Autowired
    private WmUserMapper wmUserMapper;
    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        if (dto==null) return errorResult;
        Integer userId=WmThreadLocalUtils.getUserId();
        if (userId==null) return errorResult;
        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(WmNews::getUserId,userId);
        //状态查询
        if (dto.getStatus()!=null) lambdaQueryWrapper.eq(WmNews::getStatus,dto.getStatus());
        //频道查询
        if (dto.getChannelId()!=null) lambdaQueryWrapper.eq(WmNews::getChannelId,dto.getChannelId());
        //时间查询
        if (dto.getBeginPubDate()!=null&&dto.getEndPubDate()!=null) lambdaQueryWrapper.between(WmNews::getPublishTime,dto.getBeginPubDate(),dto.getEndPubDate());
        //关键字模糊查询
        if (dto.getKeyword()!=null) lambdaQueryWrapper.like(WmNews::getTitle,dto.getKeyword());
        Page<WmNews> page = new Page<>(dto.page, dto.size);
        IPage<WmNews> resultPage=page(page,lambdaQueryWrapper);
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), (int) resultPage.getTotal());
        result.setData(resultPage.getRecords());
        result.setHost(fileServerUrl);
        return result;
    }

    @Override
    public ResponseResult saveNews(WmNewsDto wmNews, Short isSubmit) {
        if (wmNews==null||wmNews.getContent().isEmpty()) return errorResult;
        WmNews news = new WmNews();
        //将前端传过来的内容赋值到要保存到表里的对象
        BeanUtils.copyProperties(wmNews,news);
        if (WemediaContans.WM_NEWS_TYPE_AUTO.equals(wmNews.getType())){
            news.setType(null);
        }
        if (wmNews.getImages()!=null&&wmNews.getImages().size()!=0){
            StringBuffer buffer = new StringBuffer();
            wmNews.getImages().forEach(s ->buffer.append(s.replace(fileServerUrl,"")).append(","));
            news.setImages(buffer.toString().substring(0,buffer.toString().length()-1));
        }
        news.setStatus(isSubmit);
        Integer userId = WmThreadLocalUtils.getUserId();
        news.setUserId(userId);
        news.setCreatedTime(new Date());
        news.setSubmitedTime(new Date());
        news.setEnable((short) 1);
        boolean flag = false;
        //对象字段赋值完成后，还要两件事1.确定素材和新闻的关系2.保存新闻
        if (news.getId()==null){//没有又新增的文章
            flag = save(news);
        }else {
            //删除新闻和素材的关系表数据
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,news.getId()));
            //更新修改的内容
            flag=updateById(news);
        }
        if (flag){
            kafkaTemplate.send(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_TOPIC,JSON.toJSONString(news.getId()));
        }
        //将前端传过来的内容中的资源提取出来保存到集合中
        String content = wmNews.getContent();
        List<String> materialList=new ArrayList<>();
        JSONArray array = JSON.parseArray(content);
        array.forEach(m->{
            JSONObject object = JSON.parseObject(m.toString());
            if (object.get("type").equals(WemediaContans.WM_NEWS_TYPE_IMAGE)){
                materialList.add(object.get("value").toString().replace(fileServerUrl,""));
            }
        });
        //如果状态是提交且新闻内容中有资源引用
        if (isSubmit==WmNews.Status.SUBMIT.getCode()){
            if (materialList.size()!=0) {//保存新闻内容中素材和新闻的关系
                ResponseResult responseResult=saveRelativeInfoForContent(materialList,news.getId());
                if (responseResult!=null){
                    return responseResult;
                }
            }
            //保存封面资源和新闻的关系数据
            ResponseResult responseResult=saveRelativeInfoForCover(wmNews,materialList,news);
            if (responseResult!=null){
                return responseResult;
            }
        }
        return null;
    }

    @Override
    public List<Integer> findRelease() {
        List<WmNews> list = list(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getStatus, 8).lt(WmNews::getPublishTime, new Date()));
        List<Integer> collect = list.stream().map(WmNews::getId).collect(Collectors.toList());
        return collect;
    }

    @Override
    public PageResponseResult findListAndPage(NewsAuthDto dto) {
        //1.检查参数
        if (dto==null){
            ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //设置起始页
        dto.setPage((dto.getPage()-1)*dto.getSize());
        dto.setTitle("%"+dto.getTitle()+"%");

        //2.分页查询
        List<WmNewsVo> list = wmNewsMapper.findListAndPage(dto);
        //统计多少条数据
        int count = wmNewsMapper.findListCount(dto);

        //3.结果返回
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(),dto.getSize(),count);
        responseResult.setData(list);
        return responseResult;
    }

    @Override
    public WmNewsVo findWmNewsVo(Integer id) {
        //1.查询文章信息
        WmNews wmNews = getById(id);
        //2.查询作者
        WmUser wmUser = null;
        if(wmNews!=null && wmNews.getUserId() != null){
            wmUser = wmUserMapper.selectById(wmNews.getUserId());
        }

        //3.封装vo信息返回
        WmNewsVo wmNewsVo = new WmNewsVo();
        BeanUtils.copyProperties(wmNews,wmNewsVo);
        if(wmUser != null){
            wmNewsVo.setAuthorName(wmUser.getName());
        }
        return wmNewsVo;
    }

    //保存封面资源和新闻的关系数据
    //param wmNews 前端穿过来的新闻对象
    //param materialList 包含所有详情内容资源路径的集合
    //param wmNews1 要更新或保存到表里的新闻对象
    private ResponseResult saveRelativeInfoForCover(WmNewsDto wmNews, List<String> materialList, WmNews news) {
        //前端传过来的封面图集合
        List<String> images = wmNews.getImages();
        //如果前端在提交数据时,封面选择的是自动
        if (wmNews.getType()==WemediaContans.WM_NEWS_TYPE_AUTO){
            if (materialList.size()==0){//无图模式
                news.setType(WemediaContans.WM_NEWS_NONE_IMAGE);
            }else if (materialList.size()<=2){//单图模式
                news.setType(WemediaContans.WM_NEWS_SINGLE_IMAGE);
                if (images==null) images=new ArrayList<>();
                images.clear();
                images.add(materialList.get(0));
            }else {//多图模
                news.setType(WemediaContans.WM_NEWS_MANY_IMAGE);
                images=materialList.stream().limit(3).collect(Collectors.toList());
            }
            //更新已保存的新闻表中封面图的数据
            if (images.size()!=0)
                news.setImages(images.toString().replace("[","")
                        .replace("]","").replace(fileServerUrl,"")
                        .replace(" ",""));
            updateById(news);
        }
        if (images!=null&&images.size()>0){
            images=images.stream().map(i->i.replace(fileServerUrl,"")).collect(Collectors.toList());
            ResponseResult responseResult=saveRelativeInfo(images,news.getId(),WemediaContans.WM_COVER_REFERENCE);
            if (responseResult!=null){
                return responseResult;
            }
        }
        return sucResult;
    }
    //保存新闻内容中素材和新闻的关系
    private ResponseResult saveRelativeInfoForContent(List<String> materialList, Integer id) {
        return saveRelativeInfo(materialList,id,WemediaContans.WM_CONTENT_REFERENCE);
    }
    /*
    * @param materialList 内容中引用的资源路径集合
    * @param id 新闻id
    * @param wmContentReference 引用类型，当前是内容引用
    * */
    private ResponseResult saveRelativeInfo(List<String> materialList, Integer id, Short wmContentReference) {
        List<WmMaterial> list = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, materialList));
        if (list==null || list().size()==0) return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"资源错误");
        List<String> idList = new ArrayList<>();
        list.forEach(l->idList.add(l.getId().toString()));
        wmNewsMaterialMapper.saveRelationsByContent(idList,id,wmContentReference);
        return null;
    }
}
